﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace psafth.RCTiming.Main
{
    /// <summary>
    /// Interaction logic for Splash.xaml
    /// </summary>
    public partial class Splash : Window
    {
        InitOperation _operation;

        double percentageValue = 0.0;

        public DBContext DbContext
        {
            get;
            set;
        }

        public Splash(InitOperation worker)
        {
            this._operation = worker;
            this._operation.RunWorkerCompleted += _operation_RunWorkerCompleted;
            this._operation.ProgressChanged += _operation_ProgressChanged;
            this._operation.WorkerReportsProgress = true;
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(Splash_Loaded);

            this.pbDbLoad.Maximum = 100;
        }

        void _operation_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            try
            {
                if (e.UserState is double)
                {
                    percentageValue = (double)e.UserState;
                }
                else if (e.UserState is string)
                {
                    lblStatus.Content = (string)e.UserState;

                    if (this.pbDbLoad.Value + percentageValue > this.pbDbLoad.Maximum)
                        pbDbLoad.Maximum = this.pbDbLoad.Value + percentageValue;

                    this.pbDbLoad.Value = this.pbDbLoad.Value + percentageValue;
                }
                else if (e.UserState is DBContext)
                {
                    DbContext = (DBContext)e.UserState;
                }
            }
            catch (Exception ex)
            {
            }
        }

        void _operation_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                MainWindow mw = new MainWindow(DbContext);
                Close();
                mw.Show();
            }
            else
            {
                MessageBox.Show("Cannot initialise application:\n" + e.Error.Message,
                "Fatal Error", MessageBoxButton.OK, MessageBoxImage.Error);
                Close();
            }
        }

        private void MouseLeftButton_Down(object sender, MouseButtonEventArgs e)
        {
            DragMove();
        }

        void Splash_Loaded(object sender, RoutedEventArgs e)
        {
            DbContext = new DBContext();

            _operation.RunWorkerAsync(DbContext);
        }
    }
}
